<template>
  <div class="app-container" style="width: 100%;">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">

        <el-form-item style="margin-right: 15px;">
          <el-input v-model="queryParams.departName" placeholder="艺术机构名称"></el-input>
        </el-form-item>

        <el-form-item style="margin-right: 15px;">
          <el-input :disabled="artistPageData.length !== 0" v-model="queryParams.name" placeholder="活动展览名称"></el-input>
        </el-form-item>


        <el-form-item>
          <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
        </el-form-item>

        <el-form-item>
          <el-button v-if="!errors" type="primary" @click="add()"><i-ep-search />新增</el-button>
        </el-form-item>


      </el-form>
    </div>

    <el-card shadow="never" class="table-container" style="max-height: 700px;overflow-y: auto;">
      <el-table :data="eventExhibitionPageData" style="width: 100%" border>
        <el-table-column prop="departName" label="所属艺术机构名称" />
        <el-table-column prop="name" label="活动展览名称" />
        <el-table-column prop="url" label="活动展览图片">
          <template #default="scope">
            <img v-if="scope.row.url !== null && scope.row.url !== ''" :src="scope.row.url" alt=""
              style="width: 100px;height: 100px;">
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="活动开始日期" />
        <el-table-column prop="endTime" label="活动结束日期" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="sort" label="排序" />
        <el-table-column label="创建人ID">

        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <div>
              <el-button type="primary" plain size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="primary" plain size="small" @click="editTemplate(scope.row)">编辑模板</el-button>
              <el-button type="danger" plain size="small" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
    </el-card>

    <!-- 修改弹框 -->
    <el-dialog id="edit-box1" :title="dialog.title" v-model="dialog.visible" width="90%" @close="closeDialog">
      <el-form :model="editForm" label-width="160px">
        <el-form-item label="活动展览名称">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="艺术机构">
          <el-input v-model="editForm.departId" style="display: none;" />
          <el-input v-model="editForm.departName" style="width: 200px;margin-right: 15px;" disabled />
          <el-button :disabled="artistPageData.length !== 0" @click="selectDepart">选择</el-button>
        </el-form-item>
        <el-form-item label="活动展览封面图" prop="map2">
          <single-upload v-model="<string>editForm.url" />
        </el-form-item>
        <el-form-item label="参加活动艺术家" v-if="editForm.id !== null">
          <el-input v-model="editForm.artistIds" style="display: none;" />
          <el-button :disabled="artistPageData.length !== 0" @click="selectArtist"
            style="position: relative;bottom: 10px;">选择</el-button>
          <el-input type="textarea" v-model="editForm.artistNames" style="width: 200px;margin-left: 15px;" disabled />
        </el-form-item>
        <el-form-item label="活动地址" style="width: 100%;float: left;">
          <el-input v-model="editForm.address" />
        </el-form-item>
        <el-form-item label="活动开始时间" style="width: 33%;float: left;">
          <el-date-picker v-model="<string>editForm.startTime" type="date" placeholder="选择时间" format="YYYY/MM/DD"
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="活动开始结束" style="width: 33%;float: left;">
          <el-date-picker v-model="<string>editForm.endTime" type="date" placeholder="选择时间" format="YYYY/MM/DD"
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="排序" style="width: 33%;float: left;">
          <el-input v-model="editForm.sort" />
        </el-form-item>




        <el-form-item label="seo标题" style="width: 33%;float: left;">
          <el-input v-model="editForm.seoKeyworks" />
        </el-form-item>


        <el-form-item label="seo描述" style="width: 67%;float: left;">
          <el-input v-model="editForm.seoDescription" />
        </el-form-item>

        <el-form-item label="活动简述" style="width: 100%;float: left;">
          <el-input type="textarea" v-model="editForm.content" style="height: 200px;" />
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">
            取 消
          </el-button>
          <el-button type="primary" @click="editItem">
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 选择部门弹框 -->
    <el-dialog :title="groupDialog.title" v-model="groupDialog.visible" width="70%">
      <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="全部" name="all">
          <template v-for="(item, index) in departPageData">
            <el-button style="margin-bottom: 10px;" @click="confirmDepart(item.name ?? '', item.departId ?? '')">
              {{ item.name }}
            </el-button>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 选择艺术家弹框 -->
    <el-dialog :title="artistGroupDialog.title" v-model="artistGroupDialog.visible" width="70%">
      <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="全部" name="all">
          <el-checkbox-group v-model="tagscheckBoxList">
            <template v-for="(item, index) in selectArtists">
              <el-checkbox v-if="item.aid !== null" :label="<string>item.artistName" :value="item.aid?.toString()" />
            </template>
          </el-checkbox-group>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="artistGroupDialog.visible = false">
            取 消
          </el-button>
          <el-button type="primary" @click="editArtistItem">
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>
<!-- 艺术品页 -->
<script setup lang="ts">
import {
  useAppStore,
  useTagsViewStore,
  useUserStore,
  useSettingsStore,
} from "@/store";
const userStore = useUserStore();
import { useRoute } from 'vue-router';
import SingleUpload from "@/components/Upload/SingleUploadw.vue";
import EventExhibitionAPI from "@/api/eventExhibition";
import ArtistAPI from "@/api/artist";
import ArtistRelativeAPI from '@/api/artistRelative';
import type { TabsPaneContext } from 'element-plus'
import TEditor from "@/components/TEditor/TEditor.vue";
import router from "@/router";
// 艺术家接口
import ArtistsAPI from "@/api/artist";
import { Artist, ArtistPageVO, ArtistQuery } from "@/api/artist/model";
import {
  ArtistRelative
} from "@/api/artistRelative/model";

import {

  EventExhibitionForm,
  EventExhibition,
  EventExhibitionPageResult,
  EventExhibitionQuery,
  EventExhibitionPageVO
} from "@/api/eventExhibition/model";

import ArtTypesAPI from "@/api/artType";

import {

  ArtTypeForm,
  ArtType,
  ArtTypePageResult,
  ArtTypeQuery,
  ArtTypePageVO
} from "@/api/artType/model";

// 机构接口
import DepartAPI from "@/api/depart";
import { DepartForm, Depart, DepartQuery, DepartPageVO } from "@/api/depart/model";

const route = useRoute();
// 新增/修改数据选中的表填数据
const tagscheckBoxList = ref<string[]>([])
defineOptions({
  name: "EventExhibition",
  inheritAttrs: false,
});

const artistRelativeList = ref<ArtistRelative[]>()
const queryFormRef = ref(ElForm);
const departList = ref<{
  name: string,
  value: string
}[]>([])

// 机构分页数据
const departPageData = ref<DepartPageVO[]>();




const departcheckBoxList = ref<string[]>([])

// 绑定艺术家数据
const selectArtists = ref<ArtistRelative[]>([]);

const editForm = reactive<EventExhibitionForm>({

});

const loading = ref(false);
const editDialogVisible = ref(false);


const artTypeList = ref<ArtType[]>([]);




const total = ref(0);

const queryParams = reactive<EventExhibitionQuery>({
  pageNum: 1,
  pageSize: 10,

});

// 艺术机构分页查询参数
const departQueryParams = reactive<DepartQuery>({
  pageNum: 1,
  pageSize: 99,
  name: ""
});

const artistGroupDialog = reactive({
  title: '选择艺术家',
  visible: false,
});

const groupDialog = reactive({
  title: '选择机构',
  visible: false,
});
const departDialog = reactive({
  title: '选择代理机构',
  visible: false,
});
const activeName = ref('all');
// 艺术家分页数据
const artistPageData = ref<DepartPageVO[]>([]);
const editArtistForm = reactive<DepartForm>({

});

const errors = ref(false);

const eventExhibitionPageData = ref<EventExhibitionPageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

/**
 * 获取机构数据
 */
function getDepartData() {
  loading.value = true;
  DepartAPI.getPage(departQueryParams)
    .then((data: { records: DepartPageVO[] | undefined; total: number; }) => {
      departPageData.value = data.records;
    })
    .finally(() => {
      loading.value = false;
    });
}

function closeDialog() {
  editForm.content = ""
}

function editArtistItem() {
  editForm.artistIds = ""
  editForm.artistNames = ""
  for (let i = 0; i < tagscheckBoxList.value.length; i++) {
    let item = tagscheckBoxList.value[i];
    if (editForm.artistIds === "") {
      editForm.artistIds = item
      console.log(item, item, 666)
      editForm.artistNames = selectArtists.value.filter(_item => _item.aid!.toString() === item)[0].artistName
    } else {
      editForm.artistIds = editForm.artistIds + "，" + item
      editForm.artistNames = editForm.artistNames + "，" + selectArtists.value.filter(_item => _item.aid!.toString() === item)[0].artistName
    }
    console.log(item)
  }
  artistGroupDialog.visible = false;
}

/**
 * 编辑模板
 * @param row 
 */
function editTemplate(row: EventExhibition) {
  let rr = router.resolve({
    name: "EventExhibitionTemplateEdit",
    params: {
      eventId: row.eventId
    }
  });
  window.open(rr.href, '_blank');

}

/**
 * 打开新增弹框
 */
function add() {
  editForm.id = null
  editForm.did = null
  editForm.name = null;
  editForm.seoKeyworks = null;
  editForm.seoDescription = null;
  editForm.sort = null;
  editForm.updateTime = null;
  editForm.isIndex = 0;
  editForm.eventId = null;
  editForm.departId = null;
  editForm.departName = null;
  editForm.url = "";
  editForm.departId = null;
  editForm.createUser = <number>userStore.user.id
  editForm.createTime = Math.floor(Date.now() / 1000);
  editForm.createDate = null
  editForm.content = ""
  editForm.address = ""
  editForm.startTime = ""
  editForm.endTime = ""
  editForm.sort = 0;
  dialog.visible = true;
}

/**
 * 初始化选中的艺术家
 */
function initSelectArtists(departId: string | null | undefined) {
  let artistRelativeDTO = {
    departId: departId
  }
  selectArtists.value = []
  ArtistRelativeAPI.getList(artistRelativeDTO).then((data: ArtistRelative[]) => {
    selectArtists.value = data;
    console.log(selectArtists.value, "1111")
  })
}


/**
 * 打开修改弹框
 * @param row 
 */
function handleEdit(row: EventExhibition) {

  editForm.id = row.id
  editForm.did = row.did
  editForm.name = row.name;
  editForm.seoKeyworks = row.seoKeyworks;
  editForm.seoDescription = row.seoDescription;
  editForm.sort = row.sort;
  editForm.updateTime = row.updateTime;
  editForm.isIndex = row.isIndex;
  editForm.eventId = row.eventId;
  editForm.departId = row.departId;
  editForm.artistNames = row.artistNames
  editForm.artistIds = row.artistIds
  initSelectArtists(row.departId)
  editForm.departName = row.departName;
  editForm.url = row.url;
  editForm.address = row.address;
  editForm.createTime = row.createTime
  editForm.createDate = row.createDate
  editForm.content = row.content
  editForm.startTime = row.startTime
  editForm.endTime = row.endTime
  editForm.sort = row.sort;
  editForm.createUser = row.createUser

  dialog.visible = true;
}

/** 查询 */
function handleQuery() {
  loading.value = true;
  eventExhibitionPageData.value = [];
  EventExhibitionAPI.getPage(queryParams)
    .then((data) => {
      eventExhibitionPageData.value = data.records;
      for (let i = 0; i < eventExhibitionPageData.value.length; i++) {
        let item = eventExhibitionPageData.value[i];
        if (item.content === null) {
          item.content = ''
        }

      }
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
/**
 * 保存修改
 */
function editItem() {
  // 当id存在时执行修改操作，否则执行新增操作
  if (editForm.departId === null || editForm.departId === undefined || editForm.departId === "") {
    ElMessage.error("请选择活动展览所属机构")
    return
  } else {
    departPageData.value!.forEach(item => {
      if (item.departId === editForm.departId) {
        editForm.did = item.id
      }
    })
  }
  if (editForm.name === null || editForm.name === undefined || editForm.name === "") {
    ElMessage.error("请填写活动展览名称")
    return
  }
  if (editForm.url === null || editForm.url === undefined || editForm.url === "") {
    ElMessage.error("请上传活动展览封面图片")
    return
  }
  if (editForm.startTime === null || editForm.startTime === undefined || editForm.startTime === "") {
    ElMessage.error("请填写活动开始时间")
    return
  } else {
    if (editForm.startTime.indexOf("00:00:00") === -1) {
      editForm.startTime = editForm.startTime + " 00:00:00"
    }
  }
  if (editForm.endTime === null || editForm.endTime === undefined || editForm.endTime === "") {
    ElMessage.error("请填写活动结束时间")
    return
  } else {
    if (editForm.endTime.indexOf("00:00:00") === -1) {
      editForm.endTime = editForm.endTime + " 00:00:00"
    }
  }
  if (editForm.id) {
    EventExhibitionAPI.update(editForm).then(() => {
      handleQuery();
      dialog.visible = false;
    })
  } else {
    EventExhibitionAPI.add(editForm).then(() => {
      handleQuery();
      dialog.visible = false;
    })
  }

}

const handleTabClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
/**
 * 确认选择艺术家
 * @param name 
 * @param id 
 */
function confirmDepart(name: string, id: string) {
  editForm.departId = ""
  editForm.departName = ""
  editForm.departId = id;
  editForm.departName = name;
  groupDialog.visible = false;
}
function selectArtist() {
  tagscheckBoxList.value = []
  if (editForm.artistIds !== null && editForm.artistIds !== '') {
    let arr = editForm.artistIds?.split("，")
    tagscheckBoxList.value = <string[]>arr
  }
  artistGroupDialog.visible = true
  console.log("选择艺术家")
}


/**
 * 选择机构
 */
function selectDepart() {
  console.log(departPageData.value, "机构数据")
  groupDialog.visible = true;
}

function handleDelete(row: EventExhibition) {

  ElMessageBox.confirm(
    '该操作会删除该活动展览其它板块关联，是否删除该活动展览?',
    '提示',
    {
      confirmButtonText: '确 认',
      cancelButtonText: '取 消',
      type: 'warning',
      draggable: true,
    }
  ).then(() => {
    EventExhibitionAPI.delete(row).then(() => {
      ElMessage.success("删除成功");
      handleQuery();
    })

  })
}

/**
 * 获取艺术类型列表
 */
function handleGetArtTypeList() {
  let artTypeQueryParams = ref<ArtTypeQuery>({
    pageNum: 1,
    pageSize: 100
  });
  ArtTypesAPI.getList(artTypeQueryParams.value).then((data) => {
    artTypeList.value = data;
    console.log(data, 99999)
  })
}

onMounted(() => {
  handleQuery();
  handleGetArtTypeList();
  getDepartData()
});
</script>

<style>
#edit-box1 .el-dialog__body {
  height: 600px;
  overflow-y: auto;
  padding-right: 10px;
}

.tox {
  z-index: 99999 !important;
}
</style>
